import hashlib

from bs4 import BeautifulSoup
import xml.etree.ElementTree as ET

import cms_config


def trans_xml_to_dict(xml):
    """
    将微信支付交互返回的 XML 格式数据转化为 Python Dict 对象

    :param xml: 原始 XML 格式数据
    :return: dict 对象
    """

    soup = BeautifulSoup(xml, features='lxml')
    xml = soup.find('xml')
    print(xml)
    if not xml:
        return {}

    # 将 XML 数据转化为 Dict
    data = dict([(item.name, item.text) for item in xml.find_all()])
    return data


def get_sign(data={}):
    data = sorted(data.items(), key=lambda d: d[0], reverse=False)
    send_date = {}
    temp_string = ""
    for k, v in data:
        send_date[k] = v
        temp_string = temp_string + k + "=" + v + "&"
    temp_string = temp_string + "key=" + cms_config.security_key
    print(temp_string)
    return hashlib.md5(temp_string.encode("utf-8")).hexdigest().upper()


def xml_to_dict(xml_data):
    '''
    xml to dict
    :param xml_data:
    :return:
    '''
    xml_dict = {}
    root = ET.fromstring(xml_data)
    for child in root:
        xml_dict[child.tag] = child.text
    return xml_dict


def trans_dict_to_xml(data):
    """
    将 dict 对象转换成微信支付交互所需的 XML 格式数据

    :param data: dict 对象
    :return: xml 格式数据
    """

    xml = []
    for k in sorted(data.keys()):
        v = data.get(k)
        if k == 'detail' and not v.startswith('<![CDATA['):
            v = '<![CDATA[{}]]>'.format(v)
        xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
    return '<xml>{}</xml>'.format(''.join(xml))
